<template>
  <div class="container_warp">
    <div id="containerChart"></div>
    <div class="operating">
      <div class="btn-group">
        <div
          class="btn"
          title="圆形"
          @mousedown="startDrag('Circle',$event)"
        >
          <i class="iconfont icon-circle"></i>
        </div>
        <div
          class="btn"
          title="方形"
          @mousedown="startDrag('Rect',$event)"
        >
          <i class="iconfont icon-square"></i>
        </div>
      </div>
      <div class="btn-group">
        <div
          class="btn"
          @click="deleteNode()"
          style="margin-top: 5px;"
        >
          <i class="iconfont icon-shanchu"></i>
        </div>
        <div
          class="btn"
          @click="saveFlow()"
        >
          <i class="iconfont icon-baocun"></i>
        </div>
      </div>
    </div>
    <div class="drawer_container">
      <div v-if="type === 'node'">
        <div class="drawer_title">节点设置</div>
        <div class="drawer_wrap">
          <el-form
            label-position="left"
            label-width="80px"
          >
            <el-form-item label="节点文本">
              <el-input
                v-model="drawerNode.nodeText"
                @change="changeNodeText"
              ></el-input>
            </el-form-item>
            <el-form-item label="节点背景">
              <el-color-picker
                v-model="drawerNode.fill"
                @change="changeFill"
              ></el-color-picker>
            </el-form-item>
            <el-form-item label="字体大小">
              <el-slider
                v-model="drawerNode.fontSize"
                :min="10"
                :max="20"
                @change="changefontSize"
              ></el-slider>
            </el-form-item>
            <el-form-item label="字体颜色">
              <el-color-picker
                v-model="drawerNode.fontFill"
                @change="changeFontFill"
              ></el-color-picker>
            </el-form-item>
            <el-form-item label="边框宽度">
              <el-slider
                v-model="drawerNode.strokeWidth"
                :min="0"
                :max="10"
                @change="changeStrokeWidth"
              ></el-slider>
            </el-form-item>
            <el-form-item label="边框颜色">
              <el-color-picker
                v-model="drawerNode.stroke"
                @change="changeStroke"
              ></el-color-picker>
            </el-form-item>
            <el-form-item label="线条颜色">
              <el-input
                v-model="status"
                @change="changeNodeStatus"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-if="type === 'edge'">
        <el-form
          label-position="left"
          label-width="80px"
        >
          <el-form-item label="线条宽度">
            <el-slider
              v-model="drawerEdge.edgeWidth"
              :min="1"
              :max="10"
              @change="changeEdgeWidth"
            ></el-slider>
          </el-form-item>
          <el-form-item label="线条颜色">
            <el-color-picker
              v-model="drawerEdge.edgeColor"
              @change="changeEdgeColor"
            ></el-color-picker>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>

</template>

<script>
import '@antv/x6-vue-shape'
import { Graph, Shape, Addon, FunctionExt, DataUri, Cell } from '@antv/x6'
import insertCss from 'insert-css'
import { startDragToGraph } from './index'
let data = {}
export default {
  data() {
    return {
      graph: '',
      status:0,
      selectCell: {},
      drawerNode: {
        fill: '',
        nodeText: '',
        fontSize: null,
        fontFill: '',
        strokeWidth: null,
        stroke: ''
      },
      drawerEdge: {
        edgeWidth: null,
        edgeColor: ''
      },
      type: '',
      connectEdgeType: {
        //连线方式
        connector: 'normal',
        router: {
          name: ''
        }
      }
    }
  },
  methods: {
    initX6() {
      let that = this
      this.graph = new Graph({
        container: document.getElementById('containerChart'),
        width: 1700,
        height: '100%',
        resizing: {
          //节点缩放
          enabled: true,
          orthogonal: false
        },
        selecting: true,
        snapline: true, //对齐线
        interacting: function(cellView) {
          if(cellView.cell.getData() !== undefined && !cellView.cell.getData().disableMove) {
            return { nodeMovable: false}
          }
          return true
        },
        connecting: {
          anchor: 'center',
          connectionPoint: 'anchor',
          // allowBlank:true,
          snap: true,
          createEdge() {
            return new Shape.Edge({
              attrs: {
                line: {
                  stroke: '#1890ff',
                  strokeWidth: 1,
                  targetMarker: {
                    name: 'classic',
                    size: 8
                  },
                  strokeDasharray: 0, //虚线
                  style: {
                    animation: 'ant-line 30s infinite linear'
                  }
                }
              },
              label: {
                text: ''
              },
              connector: that.connectEdgeType.connector,
              router: {
                name: that.connectEdgeType.router.name || ''
              },
              zIndex: 0
            })
          }
        },
        highlighting: {
          magnetAvailable: {
            name: 'stroke',
            args: {
              padding: 4,
              attrs: {
                strokeWidth: 4,
                stroke: '#6a6c8a'
              }
            }
          }
        }
      })
      insertCss(`
        @keyframes ant-line {
          to {
            stroke-dashoffset: -1000
          }
        }
      `)
      // console.log(localStorage.getItem('flowData'));
      // console.log(JSON.parse(localStorage.getItem('flowData')));
      data = JSON.parse(localStorage.getItem('flowData'))
      console.log(data);
      data.cells.forEach(i=>{
        if(i.data?.status == 1) {
            i.attrs.body.fill = 'rgb(245, 154, 35)'
          } else if(i.data?.status == 2) {
            i.attrs.body.fill = 'rgba(75, 121, 2, 1)'
          }
      })
      // data.forEach((i) => {})
      this.graph.fromJSON(data)
      this.graph.history.redo()
      this.graph.history.undo()
      this.graph.on(
        'node:mouseenter',
        FunctionExt.debounce(() => {
          const container = document.getElementById('containerChart')
          const ports = container.querySelectorAll('.x6-port-body')
          this.showPorts(ports, true)
        }),
        500
      )
      this.graph.on('node:mouseleave', () => {
        const container = document.getElementById('containerChart')
        const ports = container.querySelectorAll('.x6-port-body')
        this.showPorts(ports, false)
      })
      this.graph.on('blank:click', () => {
        this.type = ''
      })
      this.graph.on('cell:click', ({ cell }) => {
        this.type = cell.isNode() ? 'node' : 'edge'
      })
      this.graph.on('selection:changed', (args) => {
        args.added.forEach((cell) => {
          console.log(cell)
          this.selectCell = cell
          if (cell.isNode()) {
            this.drawerNode.fill = cell.store.data.attrs.body.fill
            this.drawerNode.fontFill = cell.store.data.attrs.label.fill
            this.drawerNode.fontSize = Number(cell.store.data.attrs.label.fontSize)
            this.drawerNode.nodeText = cell.store.data.attrs.label.text
            this.drawerNode.stroke = cell.store.data.attrs.body.stroke
            this.drawerNode.strokeWidth = Number(cell.store.data.attrs.body.strokeWidth)
            // console.log(this.drawerNode)
          }
          if (cell.isEdge()) {
            console.log(cell)
            this.drawerEdge.edgeWidth = Number(cell.store.data.attrs.line.strokeWidth)
            this.drawerEdge.edgeColor = cell.store.data.attrs.line.stroke
            cell.isEdge() && cell.attr('line/strokeDasharray', 5)
            cell.addTools([
              {
                name: 'vertices',
                args: {
                  padding: 4,
                  attrs: {
                    strokeWidth: 0.1,
                    stroke: '#2d8cf0',
                    fill: '#ffffff'
                  }
                }
              }
            ])
          }
        })
        args.removed.forEach((cell) => {
          cell.isEdge() && cell.attr('line/strokeDasharray', 0) //正常线
          cell.removeTools()
        })
      })
      console.log(this.graph.getNodes())
      let cells = this.graph.getNodes()
    },
    showPorts(ports, show) {
      for (let i = 0, len = ports.length; i < len; i = i + 1) {
        ports[i].style.visibility = show ? 'visible' : 'hidden'
      }
    },
    startDrag(type, e) {
      // console.log(this.graph.getNodes().length);
      startDragToGraph(this.graph, type, e, this.graph.getNodes().length + 1)
    },
    deleteNode() {
      const cell = this.graph.getSelectedCells()
      this.graph.removeCells(cell)
      this.type = ''
    },
    saveFlow() {
      // console.log(this.graph.toJSON());
      localStorage.setItem('flowData', JSON.stringify(this.graph.toJSON()))
    },
    changeNodeText() {
      // const cell = this.graph.getSelectedCells()
      // console.log(cell);
      // cell.attr('label/text', this.drawerNode.nodeText)
      this.selectCell.attr('label/text', this.drawerNode.nodeText)
    },
    changeFill(val) {
      this.drawerNode.fill = val
      this.selectCell.attr('body/fill', val)
    },
    changefontSize(val) {
      this.selectCell.attr('label/fontSize', val)
    },
    changeFontFill(val) {
      this.drawerNode.fontFill = val
      this.selectCell.attr('label/fill', this.drawerNode.fontFill)
    },
    changeStrokeWidth(val) {
      this.selectCell.attr('body/strokeWidth', val)
    },
    changeStroke(val) {
      this.drawerNode.stroke = val
      this.selectCell.attr('body/stroke', this.drawerNode.stroke)
    },
    changeEdgeWidth(val) {
      this.drawerEdge.edgeWidth = val
      this.selectCell.attr('line/strokeWidth', this.drawerEdge.edgeWidth)
    },
    changeEdgeColor(val) {
      this.drawerEdge.stroke = val
      this.selectCell.attr('line/stroke', this.drawerEdge.stroke)
    },
    changeNodeStatus() {
      this.selectCell.data.status = this.status
      if(this.status == '1') {
        this.selectCell.attr('body/fill','rgb(245, 154, 35)' )
      }else if(this.status == '2') {
        this.selectCell.attr('rgba(75, 121, 2, 1)' )
      }
    }
  },
  mounted() {
    this.initX6()
  }
}
</script>

<style lang="less" scoped>
@import './index.less';

.drawer_container {
  max-width: 300px;
  min-width: 300px;
  .drawer_title {
    border-bottom: 1px solid #e8eaec;
    box-sizing: border-box;
    padding: 14px 16px;
    color: #333;
    font-size: 16px;
  }
  .drawer_wrap {
    box-sizing: border-box;
    padding: 20px 10px 20px 20px;
  }
}
</style>